//
//  PersonOrderListViewController.m
//  TestProject6
//
//  Created by JasonLee on 14/12/11.
//  Copyright (c) 2014年 JasonLee. All rights reserved.
//

#import "PersonOrderListViewController.h"
#import "OrderModel.h"
#import "PersonOrderDetailViewController.h"
#import "ProtocolManager.h"
#import "Common.h"
#import "DVSwitch.h"
#import "TransforController.h"

@interface PersonOrderListViewController ()<UITableViewDataSource, UITableViewDelegate>{
    PullTableView *_tableView;
    NSMutableArray *_order;
    NSMutableArray *_orderCells;
    int currRow;
    UILabel *lbFoundNoOrders;
}
@property (nonatomic,assign) int currentIndex;

@property (nonatomic,strong)NSMutableArray *dataInReturn;

@property (nonatomic, assign) int page_current;

@property (nonatomic, strong) DVSwitch *topSelectMenu;

@end

@implementation PersonOrderListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSLog(@"childViewControllers:%@", self.navigationController.childViewControllers);
    NSLog(@"Loading PersonOrderListViewController;");
    
    self.currentIndex = 0;
    self.page_current = 0;
    //[self initData];
    [self setEnableLoadMore:YES];
    self.pullTableViewDelegate = self;
    self.navigationItem.title = @"订单列表";
    CGRect screenRect = [UIScreen mainScreen].bounds;
    CGSize screenSize = screenRect.size;
    //_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height - 60)];
    self.tableView.frame = CGRectMake(0, 35, screenSize.width, screenSize.height - 100);
    _tableView = self.tableView;
    //NSLog(@"==>>PersonOrderList-->>viewDidLoad||_tableView:%f", _tableView.frame.size.height);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
//    UILabel *lbFoundNoOrders = [[UILabel alloc] initWithFrame:CGRectMake(screenSize.width / 2 - 95, screenSize.height / 2 - 70, 220, 30)];
//    lbFoundNoOrders.textColor = [UIColor grayColor];
//    lbFoundNoOrders.text = @"没有订单，赶快去下单吧！";
//    [_tableView.tableFooterView addSubview:lbFoundNoOrders];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTableviewCellLongPressed:)];
    longPress.minimumPressDuration = 1.0;
    [_tableView addGestureRecognizer:longPress];
    [self.view addSubview:_tableView];
    UIView *view_navagationBar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:-65];
    [self.view addSubview:view_navagationBar];
    [self.view setFrame:CGRectMake(0, -65, 320, 613)];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initMenuWithArray];
//    self.navigationController.navigationBar.backgroundColor  = [Common colorWithRGB:0x18aaf6];
    [self getOrderList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData:(NSArray *)array{
    //NSString *path = [[NSBundle mainBundle] pathForResource:@"PersonOrder" ofType:@"plist"];
    //NSArray *array = [NSArray arrayWithContentsOfFile:path];
    if (_order.count <= 0){
        self->_order = [[NSMutableArray alloc]init];}
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [self->_order addObject:[OrderModel statusWithDictionary:obj]];
        //NSLog(@"==>>PersonOrderList-->>initData||model:%@", [[_order objectAtIndex:idx] getOrder]);
    }];
    //NSLog(@"==>>PersonOrderList-->>initData||_order:%@",_order);
}
- (void)initMenuWithArray{
    if(self.topSelectMenu == nil){
        self.topSelectMenu = [DVSwitch switchWithStringsArray:[NSArray arrayWithObjects:@"全部",@"未支付",@"未消费", nil]];
        self.topSelectMenu.frame = CGRectMake(0, 0, 320, 35);
        self.topSelectMenu.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.sliderColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.labelTextColorInsideSlider = [UIColor colorWithRed:20/255.0 green:180/255.0 blue:220/255.0 alpha:1];
        self.topSelectMenu.labelTextColorOutsideSlider = [UIColor blackColor];
        self.topSelectMenu.cornerRadius = 5;
        [self.topSelectMenu addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:self.topSelectMenu];
    }
}

- (void)valueChanged:(id)sender{
    DVSwitch* segmentedControl = sender;
    NSLog(@"%s line:%d segment has changed to %d", __FUNCTION__, __LINE__, segmentedControl.
          selectedIndex);
    
    if(self.page_current != segmentedControl.selectedIndex){
        self.page_current = segmentedControl.selectedIndex;
//        [self.tableView setContentOffset:CGPointMake(0, -40) animated:YES];
        [self pullTableViewDidTriggerRefresh:self.tableView];
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Protocol request
- (void)getOrderList
{
    //[[ProtocolManager shareInstance] getStoreType:self selector:@selector(getOrderListCallback:)];
//    [[ProtocolManager shareInstance] getOrderList:[ProtocolManager shareInstance].loginName pageIndex:[[NSString alloc]initWithFormat:@"%i",_currentIndex + 1] andStatus:self.page_current target:self selector:@selector(getOrderListCallback:)];
    [[Common shareInstance]showLoadingViewWithMessage:@"加载中"];
    [[ProtocolManager shareInstance]getOrderList:[ProtocolManager shareInstance].loginName pageIndex:[[NSString alloc]initWithFormat:@"%i",_currentIndex + 1] andStatus:self.page_current target:self selector:@selector(getOrderListCallback:)];
}

- (void)cancelOrder:(int)index
{
    OrderModel *model = _order[index];
    NSLog(@"%@",model.order_code);
    [[Common shareInstance]showLoadingViewWithMessage:@"加载中"];
    [[ProtocolManager shareInstance] cancelOrder:model.order_code target:self selector:@selector(cancelOrderCallback:)];
}

#pragma mark - Protocol call back
- (void)getOrderListCallback:(NSDictionary*)dic
{
    NSLog(@"getOrderListCallback %@", dic);
    if ((dic[P_RESULT] == [NSNull null]) ) {
        [self resetPullTableViewState];
        return;
    }
    if (self.currentIndex == 0) {
        self.dataInReturn = [NSMutableArray array];
    }
    NSArray* orderList;
    if(![[Common valueForKey:P_RESULT dic:dic] isKindOfClass:[NSArray class]]){
        orderList = [[NSArray alloc]init];
    }else{
        orderList = [Common valueForKey:P_RESULT dic:dic];
    }
    if ([orderList isKindOfClass:[NSArray class]]) {
        [self.dataInReturn addObjectsFromArray:orderList];
        self.currentIndex++;
    }
    if(self.dataInReturn.count >= 1){
        if (orderList.count < STORE_LIST_RETURN_COUNT) {
            [self setEnableLoadMore:NO];
        }
        else {
            [self setEnableLoadMore:YES];
        }
        //NSLog(@"==>>PersonOrderList-->>getOrderListCallBack||orderList:%@", orderList);
        //NSLog(@"==>>PersonOrderList-->>getOrderListCallBack||dataInReturn:%@", _dataInReturn);
        [self resetPullTableViewState];
        [self initData:orderList];
        if(lbFoundNoOrders != nil){
            [lbFoundNoOrders removeFromSuperview];
        }
    }else{
        if(lbFoundNoOrders == nil){
            lbFoundNoOrders = [[UILabel alloc] initWithFrame:CGRectMake(0, 120, 320, 30)];
            lbFoundNoOrders.textColor = [UIColor grayColor];
            lbFoundNoOrders.text = @"没有订单，赶快去下单吧！";
            lbFoundNoOrders.textAlignment = UITextAlignmentCenter;
            [_tableView.tableFooterView addSubview:lbFoundNoOrders];
            [self setEnableLoadMore:NO];
        }else{
            [_tableView.tableFooterView addSubview:lbFoundNoOrders];
        }
    }
    [_tableView reloadData];
    [[Common shareInstance]stopLoadingView];
//    [_tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)cancelOrderCallback:(NSDictionary*)dic
{
    NSLog(@"cancelOrderCallback %@", dic);
    if (dic == nil) {
        return;
    }
    OrderModel *model = _order[currRow];
    int status = [[Common valueForKey:P_ORDERSTATUS dic:dic] integerValue];
    model.order_action = [Common valueForKey:P_ORDERSTATUSNAME dic:dic];
    if (model.order_status == status) {
        [[Common shareInstance] showAlertViewWithTitle:@"此订单不可取消" text:nil dismissTime:0.8];
    } else {
        model.order_status = status;
        model.order_action_color = [UIColor grayColor];
        [[Common shareInstance] showAlertViewWithTitle:@"此订单取消成功" text:nil dismissTime:0.8];
        [_tableView reloadData];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //NSLog(@"%lu", (unsigned long)_order.count);
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataInReturn.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    OrderModel *model = _order[indexPath.row];
    CGSize cellSize;
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    cellSize = cell.frame.size;
    UILabel *_lbCode = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 150, 30)];
    _lbCode.text = model.order_code;
    _lbCode.font = [UIFont fontWithName:@"Arial" size:12.0f];
    _lbCode.textColor = [UIColor grayColor];
    [cell addSubview:_lbCode];
    
    UILabel *_lbDatetime = [[UILabel alloc]init];
    _lbDatetime.text = model.order_datetime;
    _lbDatetime.font = [UIFont fontWithName:@"Arial" size:12.0f];
    _lbDatetime.textColor = [UIColor grayColor];
    CGSize titleSize = [model.order_datetime sizeWithFont:_lbDatetime.font constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
    _lbDatetime.frame = CGRectMake(cellSize.width - titleSize.width - 10, 5, titleSize.width, 30);
    [cell addSubview:_lbDatetime];
    
    UILabel *_lbSeller = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(_lbCode.frame) + 5, 300, 30)];
    _lbSeller.text = model.order_seller;
    _lbSeller.font = [UIFont fontWithName:@"宋体" size:14.0f];
    [cell addSubview:_lbSeller];
    
    UILabel *_lbPrice = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(_lbSeller.frame) + 25, 45, 30)];
    _lbPrice.text = @"总价：";
    _lbPrice.textColor = [UIColor grayColor];
    _lbPrice.font = [UIFont fontWithName:@"Arial" size:14.0f];
    [cell addSubview:_lbPrice];
    UILabel *_lbTotalPrice = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_lbPrice.frame), CGRectGetMinY(_lbPrice.frame), 100, 30)];
    NSString *string = [NSString stringWithFormat:@"%@元", model.order_totalPrice];
    _lbTotalPrice.text = string;
    _lbTotalPrice.font = [UIFont fontWithName:@"Arial" size:16.0f];
    [cell addSubview:_lbTotalPrice];
    
    UILabel *_lbAction = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
//    _lbAction.text = model.order_action;
    _lbAction.text = [Common valueForKey:@"orderStatusName" dic:self.dataInReturn[indexPath.row]];
    _lbAction.font = [UIFont fontWithName:@"Arial" size:14.0f];
    //_lbAction.textColor = [UIColor colorWithRed:25/255.0 green:180/255.0 blue:220/255.0 alpha:1];
    _lbAction.textColor = model.order_action_color;
    _lbAction.textAlignment = UITextAlignmentRight;
    titleSize = [model.order_action sizeWithFont:_lbAction.font constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
    _lbAction.frame = CGRectMake(cellSize.width - titleSize.width - 10, CGRectGetMinY(_lbTotalPrice.frame), titleSize.width, 30);
    [cell addSubview:_lbAction];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%s || indexPath:%d", __FUNCTION__, indexPath.row);
    OrderModel *orderModel = _order[indexPath.row];
    PersonOrderDetailViewController *personOrderDetailController = [[PersonOrderDetailViewController alloc]init];
    personOrderDetailController.model = orderModel;
    [self.navigationController pushViewController:personOrderDetailController animated:YES];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

#pragma mark - LongPressDelegate
- (void)handleTableviewCellLongPressed:(UILongPressGestureRecognizer*)gestureRecognizer
{
    NSLog(@"==>>PersonOrderDetailViewController-->>handleTableviewCellLongPressed||gestureRecognizer:%@",gestureRecognizer);
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan){
        NSLog(@"UIGestureRecognizerStateBegan");
        CGPoint point=[gestureRecognizer locationInView:_tableView];
        NSLog(@" CGPoint ponit=%f %f",point.x,point.y);
        NSIndexPath* path=[_tableView indexPathForRowAtPoint:point];
        NSLog(@"row:%d",path.row);
        currRow = path.row;
        UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"取消订单？" message:nil delegate:self cancelButtonTitle:@"YES"otherButtonTitles:@"NO",nil];
        [alert show];
    }
}

#pragma mark - AlertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            [[Common shareInstance] showLoadingViewWithMessage:nil];
            [self cancelOrder:currRow];
            break;
            
        default:
            break;
    }
}

#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
    self.currentIndex = 0;
    [self setPullTableIsLoadMore:YES];
    [self getOrderList];
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
    [self getOrderList];
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}

@end
